<?php

namespace Frieza\Modules\Position\Actions;

use Doraemon\cache\Queue;
use Doraemon\model\Member;
use Illuminate\Http\Request;
use Encore\Admin\Actions\RowAction;
use Hhz\AdministrativeRegion\Region;

class BrandChangeArea extends RowAction
{
    public $name = '修改地理位置';

    //该修改地址的方法仅适用于品牌用户,用于解决品牌用户在认证后就无法修改地理位置的问题
    public function handle($uid, Request $request)
    {
        //获取城市信息
        $area_code = $request->get('city');
        if (empty($area_code)) {
            return $this->response()->error('请选择城市')->refresh();
        }
        $new_info['area_code'] = $area_code;
        $new_info['area'] = Region::getOldCodeByAreaCode($area_code);
        //删除用户的缓存数据
        Queue::insertQueue('User/delUserinfoCache', [
            'uid' => $uid,
        ], Queue::QUEUE_COMMON);
        //修改用户数据库的信息
        $result = Member::updateUserInfo($uid, $new_info);
        if ($result) {
            return $this->response()->success('品牌用户地理位置修改成功!')->refresh();
        }

        return $this->response()->error('品牌用户地理位置修改失败,请稍后重试!');

    }

    public function retrieveModel(Request $request)
    {
        if (!$key = $request->get('_key')) {
            return false;
        }
        return $key;
    }

    public function form($request): void
    {
        $uid = $request->uid;
        //获取该用户的默认地理位置
        $user_info = Member::getUserInfo($uid);
        $user_area_code = $user_info['area_code'] ?? '';
        $top = Region::getProvincesList();
        $province_code = $user_area_code ? Region::getProvinceCode($user_area_code) : '';
        $city_code = $user_area_code ? Region::getCityCode($user_area_code) : '';
        $all_city = Region::getCityListByProvinceCode((string)$province_code);
        $this->select('province', '请选择省份')->options($top)->load('city',
            '/admin/extend/area/get')->default($province_code);
        $this->select('city', '城市')->options($all_city)->default($city_code);
    }
}
